<?php

/**
 * contact : 刘经理 19326416371
 * company : 版权所属 四川北星惯牌科技有限公司
 **/

namespace app\api\controller;

use app\api\validate\Cultivate;
use app\api\validate\UserDestroy;
use app\common\constant\Constant;
use app\common\controller\Api;
use app\common\library\Auth;
use app\common\library\Authentication\Aliauth;
use app\common\library\Ems;
use app\common\library\Map\Map;
use app\common\library\Sms;
use app\common\library\Wechat;
use app\common\manager\assistant\AssistantManager;
use app\common\manager\AuthenticationManager;
use app\common\manager\BaseManager;
use app\common\manager\CultivateManager;
use app\common\manager\GroupManager;
use app\common\manager\MatchManager;
use app\common\manager\OrderManager;
use app\common\manager\ProxyManager;
use app\common\manager\UserAccountManager;
use app\common\manager\UserMoneyManager;
use app\common\manager\WithdrawManager;
use app\common\manager\WriteOffManager;
use app\common\model\Proxy;
use app\common\model\Region;
use think\Config;
use think\Exception;
use think\Validate;

/**
 * 会员接口
 */
class User extends Api
{
    protected $noNeedLogin = ['login', 'mobilelogin', 'register', 'resetpwd', 'changeemail', 'changemobile', 'third'];
    protected $noNeedRight = '*';

    public function _initialize()
    {
        parent::_initialize();

        if (!Config::get('fastadmin.usercenter')) {
            $this->error(__('User center already closed'));
        }

    }

    /**
     * 会员中心
     */
    public function index()
    {
        $this->success('', ['welcome' => $this->auth->nickname]);
    }

    /**
     * 会员登录
     *
     * @ApiMethod (POST)
     * @param string $account  账号
     * @param string $password 密码
     */
    public function login()
    {
        $account = $this->request->post('account');
        $password = $this->request->post('password');
        if (!$account || !$password) {
            $this->error(__('Invalid parameters'));
        }
        $ret = $this->auth->login($account, $password);
        if ($ret) {
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('Logged in successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    public function userinfo()
    {
        $userInfo = $this->auth->getUserinfo();
        $data = ['userinfo' => $userInfo];
        $this->success('获取成功', $data);
    }

    /**
     * 手机验证码密码注册及登陆
     * @param $mobile 手机号
     * @param $captcha 手机验证码
     * @param $password 密码
     * @param $invite 邀请码
     * @return void
     */
    public function mobilelogin()
    {
        $mobile = $this->request->post('mobile');
        $captcha = $this->request->post('captcha');
        $password = $this->request->post('password');
        $invite = $this->request->post('invite');
        $type = $this->request->post('type');

        $validate = new \app\api\validate\User();
        if(!$validate->check(['mobile' => $mobile, 'captcha' => $captcha,'invite' => $invite])){
            $this->error($validate->getError());
        }

        $user = \app\common\model\User::getByMobile($mobile);
        if ($user) {

            /*if ($user->password != $this->getEncryptPassword($password, $user->salt)) {
                $this->error('Password is incorrect');
            }*/

            if ($user->status != 'normal') {
                $this->error(__('Account is locked'));
            }
            //如果已经有账号则直接登录
            $ret = $this->auth->direct($user->id);
        } else {
            $ret = $this->auth->register($mobile, $password, '', $mobile, ['invite'=>$invite,'type'=>$type]);
        }
        if ($ret) {
            Sms::flush($mobile, 'mobilelogin');
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('Logged in successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 注册会员
     *
     * @ApiMethod (POST)
     * @param string $username 用户名
     * @param string $password 密码
     * @param string $email    邮箱
     * @param string $mobile   手机号
     * @param string $code     验证码
     */
    public function register()
    {
        $username = $this->request->post('username');
        $password = $this->request->post('password');
        $email = $this->request->post('email');
        $mobile = $this->request->post('mobile');
        $code = $this->request->post('code');
        if (!$username || !$password) {
            $this->error(__('Invalid parameters'));
        }
        if ($email && !Validate::is($email, "email")) {
            $this->error(__('Email is incorrect'));
        }
        if ($mobile && !Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        $ret = Sms::check($mobile, $code, 'register');
        if (!$ret) {
            $this->error(__('Captcha is incorrect'));
        }
        $ret = $this->auth->register($username, $password, $email, $mobile, []);
        if ($ret) {
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('Sign up successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 退出登录
     * @ApiMethod (POST)
     */
    public function logout()
    {
        if (!$this->request->isPost()) {
            $this->error(__('Invalid parameters'));
        }
        $this->auth->logout();
        $this->success(__('Logout successful'));
    }

    /**
     * 修改会员个人信息
     *
     * @ApiMethod (POST)
     * @param string $avatar   头像地址
     * @param string $username 用户名
     * @param string $nickname 昵称
     * @param string $bio      个人简介
     */
    public function profile()
    {
        $user = $this->auth->getUser();
        $username = $this->request->post('username');
        $nickname = $this->request->post('nickname');
        $gender = $this->request->post('gender');
        $province = $this->request->post('province');
        $city = $this->request->post('city');
        $district = $this->request->post('district');
        $birthday = $this->request->post('birthday');
        $bio = $this->request->post('bio');
        $avatar = $this->request->post('avatar', '', 'trim,strip_tags,htmlspecialchars');
        if ($username) {
            $exists = \app\common\model\User::where('username', $username)->where('id', '<>', $this->auth->id)->find();
            if ($exists) {
                $this->error(__('Username already exists'));
            }
            $user->username = $username;
        }
        if ($nickname) {
            $exists = \app\common\model\User::where('nickname', $nickname)->where('id', '<>', $this->auth->id)->find();
            if ($exists) {
                $this->error(__('Nickname already exists'));
            }
            $user->nickname = $nickname;
        }
        $user->birthday = $birthday;
        $user->gender=$gender;
        $user->province=$province;
        $user->city=$city;
        $user->district=$district;
        $user->bio = $bio;
        $user->avatar = $avatar;
        $user->save();
        $this->success();
    }

    /**
     * 修改邮箱
     *
     * @ApiMethod (POST)
     * @param string $email   邮箱
     * @param string $captcha 验证码
     */
    public function changeemail()
    {
        $user = $this->auth->getUser();
        $email = $this->request->post('email');
        $captcha = $this->request->post('captcha');
        if (!$email || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::is($email, "email")) {
            $this->error(__('Email is incorrect'));
        }
        if (\app\common\model\User::where('email', $email)->where('id', '<>', $user->id)->find()) {
            $this->error(__('Email already exists'));
        }
        $result = Ems::check($email, $captcha, 'changeemail');
        if (!$result) {
            $this->error(__('Captcha is incorrect'));
        }
        $verification = $user->verification;
        $verification->email = 1;
        $user->verification = $verification;
        $user->email = $email;
        $user->save();

        Ems::flush($email, 'changeemail');
        $this->success();
    }

    /**
     * 修改手机号
     *
     * @ApiMethod (POST)
     * @param string $mobile  手机号
     * @param string $captcha 验证码
     */
    public function changemobile()
    {
        $user = $this->auth->getUser();
        $mobile = $this->request->post('mobile');
        $captcha = $this->request->post('captcha');
        if (!$mobile || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        if (\app\common\model\User::where('mobile', $mobile)->where('id', '<>', $user->id)->find()) {
            $this->error(__('Mobile already exists'));
        }
        $result = Sms::check($mobile, $captcha, 'changemobile');
        if (!$result) {
            $this->error(__('Captcha is incorrect'));
        }
        $verification = $user->verification;
        $verification->mobile = 1;
        $user->verification = $verification;
        $user->mobile = $mobile;
        $user->save();

        Sms::flush($mobile, 'changemobile');
        $this->success();
    }

    /**
     * 第三方登录
     *
     * @ApiMethod (POST)
     * @param string $platform 平台名称
     * @param string $code     Code码
     */
    public function third()
    {
        $url = url('user/index');
        $platform = $this->request->post("platform");
        $code = $this->request->post("code");
        $config = get_addon_config('third');
        if (!$config || !isset($config[$platform])) {
            $this->error(__('Invalid parameters'));
        }
        $app = new \addons\third\library\Application($config);
        //通过code换access_token和绑定会员
        $result = $app->{$platform}->getUserInfo(['code' => $code]);
        if ($result) {
            $loginret = \addons\third\library\Service::connect($platform, $result);
            if ($loginret) {
                $data = [
                    'userinfo'  => $this->auth->getUserinfo(),
                    'thirdinfo' => $result
                ];
                $this->success(__('Logged in successful'), $data);
            }
        }
        $this->error(__('Operation failed'), $url);
    }

    /**
     * 重置密码
     *
     * @ApiMethod (POST)
     * @param string $mobile      手机号
     * @param string $newpassword 新密码
     * @param string $captcha     验证码
     */
    public function resetpwd()
    {
        $type = $this->request->post("type", "mobile");
        $mobile = $this->request->post("mobile");
        $email = $this->request->post("email");
        $newpassword = $this->request->post("newpassword");
        $captcha = $this->request->post("captcha");
        if (!$newpassword || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        //验证Token
        if (!Validate::make()->check(['newpassword' => $newpassword], ['newpassword' => 'require|regex:\S{6,30}'])) {
            $this->error(__('Password must be 6 to 30 characters'));
        }
        if ($type == 'mobile') {
            if (!Validate::regex($mobile, "^1\d{10}$")) {
                $this->error(__('Mobile is incorrect'));
            }
            $user = \app\common\model\User::getByMobile($mobile);
            if (!$user) {
                $this->error(__('User not found'));
            }
            $ret = Sms::check($mobile, $captcha, 'resetpwd');
            if (!$ret) {
                $this->error(__('Captcha is incorrect'));
            }
            Sms::flush($mobile, 'resetpwd');
        } else {
            if (!Validate::is($email, "email")) {
                $this->error(__('Email is incorrect'));
            }
            $user = \app\common\model\User::getByEmail($email);
            if (!$user) {
                $this->error(__('User not found'));
            }
            $ret = Ems::check($email, $captcha, 'resetpwd');
            if (!$ret) {
                $this->error(__('Captcha is incorrect'));
            }
            Ems::flush($email, 'resetpwd');
        }
        //模拟一次登录
        $this->auth->direct($user->id);
        $ret = $this->auth->changepwd($newpassword, '', true);
        if ($ret) {
            $this->success(__('Reset password successful'));
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 获取用户账户信息
     * @return void
     */
    public function account()
    {
        $uid = $this->user_id;
        try {
            $result = UserAccountManager::getAccount($uid);
            if ($result['code']==BaseManager::$successCode){
                $this->success($result['message'],$result['data']);
            }else{
                throw new Exception($result['message']);
            }

        }catch (Exception $exception){
            $this->error($exception->getMessage());
        }
    }

    /**
     * 实名认证接口
     * @method post
     * @name 姓名
     * @idcard 身份证
     * @return void
     */
    public function authentication()
    {

        $name = $this->request->post('name');
        $idcard = $this->request->post('idcard');
        $captcha = $this->request->post('captcha');
        $mobile = $this->request->post('mobile') ?? '';
        $user_id = $this->user_id;

        try {
            $user = \app\common\model\User::where('id', $user_id)->find();
            if (!$mobile && $user){
                $mobile = $user['mobile'];
            }
            $authentication = new \app\api\validate\Authentication();
            if(!$authentication->check(['name'=>$name,'idcard'=>$idcard,'captcha'=>$captcha,'mobile'=>$mobile])){
                throw new Exception($authentication->getError());
            }

            if ($this->user->is_authentication){
                throw new Exception('您已实名认证，请勿重复操作');
            }

            $authResult = Aliauth::main($name,$idcard,$mobile);
            if ((int)$authResult['data']['bizCode'] != Aliauth::biz_code_success) {
                throw new Exception(Aliauth::biz_code_arr[$authResult['data']['bizCode']]['message'].','.Aliauth::biz_subCode_message[$authResult['data']['subCode']]['message']);
            }

            $result = AuthenticationManager::AuthRealName($user_id,$name,$idcard,$mobile,$authResult['data']);
            if ($result['code'] == 1) {
                $this->success($result['message']);
            }else{
                throw new Exception($result['message']);
            }
        }catch (Exception $exception){
            $this->error($exception->getMessage());
        }
    }

    public function moneyLog()
    {
        $page = $this->request->post('page') ?? 1;
        if ($page < 1){
            $page = 1;
        }
        $type = $this->request->post('type') ? $this->request->post('type') : 0;
        $detail = $this->request->post('detail') ? $this->request->post('detail') : 0;
        $userId = $this->user_id;
        try {
            $result = UserAccountManager::moneyLog($userId,$type,$detail,[],$page);
            if ($result['code'] == BaseManager::$successCode) {
                $this->success($result['message'],$result['data']);
            }else{
                throw new Exception($result['message']);
            }
        }catch (Exception $exception){
            $this->error($exception->getMessage());
        }
    }


    public function scoreLog()
    {
        $page = $this->request->post('page') ?? 1;
        if ($page < 1){
            $page = 1;
        }
        $type = $this->request->post('type') ? $this->request->post('type') : 0;
        $detail = $this->request->post('detail') ? $this->request->post('detail') : 0;
        $userId = $this->user_id;
        try {
            $result = UserAccountManager::scoreLog($userId,$type,$detail,[],$page);
            if ($result['code'] == BaseManager::$successCode) {
                $this->success($result['message'],$result['data']);
            }else{
                throw new Exception($result['message']);
            }
        }catch (Exception $exception){
            $this->error($exception->getMessage());
        }
    }

    public function getOpenId()
    {
        try {
            $code = $this->request->post('code');
            if (!$code){
                $this->error('code码不能为空');
            }
            $result = UserAccountManager::getUserOpenId($this->user,$code);
            if ($result['code'] == BaseManager::$successCode) {
                $this->success($result['message']);
            }else{
                throw new Exception($result['message']);
            }
        }catch (Exception $exception){
            $this->error($exception->getMessage().$exception->getFile().$exception->getLine());
        }

    }

    public function team()
    {
        $page = $this->request->post('page') ?? 1;
        $status = $this->request->post('status');//1=待支付,2=组队中,3=进行中,4=已结束,5=已取消
        $type = $this->request->post('type');//1=initiator,2=join
        $long = $this->request->post('lng')??0.00;
        $lat = $this->request->post('lat')??0.00;
        if ($page < 1){
            $page = 1;
        }
        try {
            $result = GroupManager::teamInfoByUser($this->user,$long,$lat,$type,$status,$page);
            if ($result['code'] == BaseManager::$successCode) {
                $this->success($result['message'],$result['data']);
            }else{
                throw new Exception($result['message']);
            }
        }catch (Exception $exception){
            $this->error($exception->getMessage().$exception->getFile().$exception->getLine());
        }
    }

    /**
     * 取消
     * @return void
     */
    public function cancel()
    {
        $id = $this->request->post('id');
        try {
            $result = GroupManager::cancelUserTeam($this->user,$id);
            if ($result['code']==BaseManager::$successCode){
                $this->success($result['message']);
            }else{
                throw new Exception($result['message']);
            }
        }catch (Exception $exception){
            $this->error($exception->getMessage());
        }

    }

    public function getWriteOff()
    {
        $user = $this->user;
        $id = $this->request->post('id');
        try {
            $result = GroupManager::getWriteOff($user,$id);
            if ($result['code'] == BaseManager::$successCode){
                $this->success($result['message'],$result['data']);
            }else{
                throw new Exception($result['message']);
            }
        }catch (Exception $exception){
            $this->error($exception->getMessage());
        }
    }

    public function writeOff()
    {
        $user = $this->user;
        $verify_code = $this->request->post('verify_code');
        try {
            $result = WriteOffManager::writeOff($user,$verify_code);
            if ($result['code'] == BaseManager::$successCode){
                $this->success($result['message']);
            }else{
                throw new Exception($result['message']);
            }
        }catch (Exception $exception){
            $this->error($exception->getMessage());
        }
    }

    public function invite()
    {
        $user = $this->user;
        try {
            $wechat = new Wechat();
            $page = config('wechat.invite_page');
            $scene = ['t'=>1,'i'=>$user->invite_code];
            $image = $result = $wechat->getUnlimited(http_build_query($scene),$page);
            $result = json_decode($result,true);
            if (json_last_error() == JSON_ERROR_NONE){
                if (isset($result['errcode']) && !empty($result['errcode'])){
                    throw new Exception($result['errmsg']);
                }
            }else{
                $this->success('获取成功',['image'=>base64_encode($image)]);
            }
        }catch (Exception $exception){
            $this->error($exception->getMessage());
        }
    }


    public function order()
    {
        $user = $this->user;
        $page = $this->request->post('page') ?? 1;
        if ($page < 1){
            $page = 1;
        }
        $type = $this->request->post('type') ?? 0;
        $status = $this->request->post('status') ?? 0;
        try {
            $result = OrderManager::UserOrder($user,$type,$status,$page);
            if ($result['code'] == BaseManager::$successCode){
                $this->success($result['message'],$result['data']);
            }else{
                throw new Exception($result['message']);
            }
        }catch (Exception $exception){
            $this->error($exception->getMessage());
        }
    }

    public function withdraw()
    {
        $page = $this->request->post('page') ?? 1;
        if ($page < 1){
            $page = 1;
        }
        $type = $this->request->post('type') ?? 'wechat';
        $status = $this->request->post('status') ?? null;
        try {
            $result = WithdrawManager::withdrawList($this->user,$status,$type,$page);
            if ($result['code']==BaseManager::$successCode){
                $this->success($result['message'],$result['data']);
            }else{
                throw new Exception($result['message']);
            }
        }catch (Exception $exception){
            $this->error($exception->getMessage());
        }
    }

    public function match()
    {
        $page = $this->request->post('page') ?? 1;
        if ($page < 1){
            $page = 1;
        }

        try {
            $result = MatchManager::matchByUser($this->user,$page);
            if ($result['code']==BaseManager::$successCode){
                $this->success($result['message'],$result['data']);
            }else{
                throw new Exception($result['message']);
            }
        }catch (Exception $exception){
            $this->error($exception->getMessage());
        }
    }

    public function cancelMatch()
    {
        $id = $this->request->post('id');
        try {
            $result = MatchManager::cancelUserMatch($this->user,$id);
            if ($result['code']==BaseManager::$successCode){
                $this->success($result['message']);
            }else{
                throw new Exception($result['message']);
            }
        }catch (Exception $exception){
            $this->error($exception->getMessage());
        }
    }

    public function destroy(){
        try {
            $validate = new UserDestroy();
            if (!$validate->check(['mobile'=>$this->user->mobile,'captcha'=>$this->request->post('captcha')])){
                throw new Exception($validate->getError());
            }
            $auth = Auth::instance();
            if($auth->destroy($this->user_id)){
                exit(json_encode(['code'=>1,'message'=>'注销成功','data'=>null,'time'=>time()]));
            }else{
                throw new Exception($auth->getError());
            }
        }catch (\Exception $exception){
            $this->error($exception->getMessage());
        }
    }

    /**
     * 用户代理申请
     * @return void
     */
    public function proxyApply()
    {
        try {
            $province = $this->request->post('province') ?? 0;
            $city = $this->request->post('city') ?? 0;
            $district = $this->request->post('district') ?? 0;
            if (!$province || !$city || !$district){
                throw new Exception('请选择省市区');
            }
            $result = ProxyManager::proxy($this->user,['province'=>$province,'city'=>$city,'district'=>$district]);
            if ($result['code'] == BaseManager::$successCode){
                $this->success($result['message'],$result['data']);
            }else{
                throw new Exception($result['message']);
            }
        }catch (Exception $exception){
            $this->error($exception->getMessage());
        }
    }

    /**
     * 获取用户最近申请记录详情
     * @return void
     */
    public function ProxyApplyDetail()
    {
        try {
            $result = ProxyManager::getProxyDetail($this->user);
            if ($result['code']==BaseManager::$successCode){
                $this->success($result['message'],$result['data']);
            }else{
                throw new Exception($result['message']);
            }
        }catch (Exception $exception){
            $this->error($exception->getMessage());
        }
    }

    public function proxyUserList()
    {
        $page = $this->request->post('page');
        try {
            if ($page < 1)
                $page  = 1;
            $result = ProxyManager::ProxyUser($this->user->id,$page);
            if ($result['code']==BaseManager::$successCode){
                $this->success($result['message'],$result['data']);
            }else{
                throw new Exception($result['message']);
            }
        }catch (Exception $exception){
            $this->error($exception->getMessage());
        }
    }

    public function proxyMoneyLog()
    {
        $page = $this->request->post('page') ?? 1;
        if ($page < 1){
            $page = 1;
        }
        $userId = $this->user_id;
        try {
            $result = UserAccountManager::moneyLog($userId,UserMoneyManager::TYPE_INCREASE,$detail=0,['detail'=>['in',[UserMoneyManager::TYPE_PROXY_RECHARGE_REWARD,UserMoneyManager::TYPE_PROXY_STORE_TEAM_REWARD,UserMoneyManager::TYPE_PROXY_CAPTAIN_TEAM_REWARD]]],$page);
            if ($result['code'] == BaseManager::$successCode) {
                $this->success($result['message'],$result['data']);
            }else{
                throw new Exception($result['message']);
            }
        }catch (Exception $exception){
            $this->error($exception->getMessage());
        }
    }

    public function purchaseRecord()
    {
        $page = $this->request->post('page') ?? 1;
        if ($page < 1){
            $page = 1;
        }
        $userId = $this->user_id;
        try {
            $result = UserAccountManager::PurchaseRecord($userId,$page);
            if ($result['code'] == BaseManager::$successCode) {
                $this->success($result['message'],$result['data']);
            }else{
                throw new Exception($result['message']);
            }
        }catch (Exception $exception){
            $this->error($exception->getMessage());
        }
    }

    public function setAddress()
    {
        $lat = $this->request->post('lat');
        $lng = $this->request->post('lng');
        try {
            if ($lat && $lng) {
                if ($this->user->province && $this->user->city) {
                    $this->error('请不要重复设置地址');
                }
                $addressConfig = get_addon_config('address');
                $map = new Map($addressConfig);
                $location = $lat.','.$lng;
                $map->getInfoByLocation($location);
                $response = $map->getResponse();
                $response = json_decode($response, true);
                if (!empty($response) && isset($response['status']) && $response['status'] == 0 && isset($response['result']) && isset($response['result']['address_component'])) {
                    $province = $response['result']['address_component']['province'] ?: '';
                    $city = $response['result']['address_component']['city'] ?: '';
                    $district = $response['result']['address_component']['district'] ?: '';
                    $set['province'] = Region::where('name',$province)->value('city_code');
                    $set['city'] = Region::where('name',$city)->value('city_code');
                    $set['district'] = Region::where('name',$district)->value('city_code');
                    if ($set){
                        \app\common\model\User::where('id',$this->user_id)->update($set);
                        $this->success('设置成功',$set);
                    }else{
                        $this->error('参数错误');
                    }
                }
                $this->error('参数错误');
            }
            $this->error('参数错误');
        }catch (Exception $exception){
            $this->error($exception->getMessage());
        }
    }

    public function getAssistantOrder()
    {
        $page = $this->request->param('page',1);
        $status = $this->request->param('status',-1);
        try {
            $result = AssistantManager::getUserOrderList($this->user,$status,$page);
            if ($result['code'] == BaseManager::$successCode) {
                $this->success($result['message'],$result['data']);
            } else {
                throw new Exception($result['message']);
            }
        } catch (Exception $exception) {
            $this->error($exception->getMessage());
        }
    }


    public function refundOrder()
    {
        try {
            $result = AssistantManager::refundUserOrder($this->user, $this->request->param('id'));
            if ($result['code'] == BaseManager::$successCode) {
                $this->success($result['message']);
            } else {
                throw new Exception($result['message']);
            }
        }catch (Exception $exception){
            $this->error($exception->getMessage());
        }
    }

    public function cultivate()
    {
        $name = $this->request->param('name');
        $mobile = $this->request->param('mobile');
        $captcha = $this->request->param('captcha');
        $type = $this->request->param('type');
        $province = $this->request->param('province');
        $city = $this->request->param('city');
        $district = $this->request->param('district');
        try {
            $data = ['name' => $name,'mobile' => $mobile, 'type'=>$type,'captcha' => $captcha,'province' => $province,'city' => $city,'district' => $district];
            $cultivate = new Cultivate();
            if (!$cultivate->check($data)) {
                throw new Exception($cultivate->getError());
            }
            unset($data['captcha']);
            $result = CultivateManager::apply($this->user,$data);
            if ($result['code'] == BaseManager::$successCode) {
                $this->success($result['message']);
            } else {
                throw new Exception($result['message']);
            }
        }catch (Exception $exception){
            $this->error($exception->getMessage());
        }
    }
}
